<template>
  <!--分配答辩组学生-->
  <div class="assign-reply-stu">
    <InnerBreadcrumb v-model="indexKey" :path="breadPath" :label-args="{name: actionType === 'ADD' ? $t('graduationDesign.add'): $t('graduationDesign.modify')}" :showBack="true" />
    <div class="edu-page-warp" v-show="indexKey === 'MAIN'">
      <!--查看老师/学生详情弹框-->
      <TeacherStuInfoDialog :viewDetailData="viewDetailData" :dialogVisible="dialogVisible" :viewType="viewType" @taacher-stu-close="closeDialog"></TeacherStuInfoDialog>

      <condition-card @reset="reset" @search="searchList" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.graduationYear')">
              <el-date-picker class="search-item" :clearable="false" v-model="queryForm.graduationYear" @change="handleGradeChange" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.college')">
              <el-select v-model="queryForm.collegeId" filterable @change="handleCollegeChange" class="search-item" clearable>
                <el-option v-for="item in source.collegeOptions" :key="item.collegeId" :label="item.collegeIdI18n" :value="item.collegeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.major')">
              <el-select v-model="queryForm.subjectId" filterable class="search-item" clearable>
                <el-option v-for="item in source.subjectOptions" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.replyTime')">
              <el-date-picker v-model="queryForm.defenseStartTime" class="search-item" type="date" clearable value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('graduationDesign.pleaseChoose')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.replyGroup')">
              <el-input v-model="queryForm.defenseGroupName" :placeholder="$t('graduationDesign.pleaseEnter')" class="search-item" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card>
        <div class="edu-page-title">{{$t('graduationDesign.assignReplyStudent')}}</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
            <el-input v-model="queryForm.defenseGroupLeaderName" :placeholder="$t('graduationDesign.pleaseEnterReplyLeaderName')" style="width:300px" @keyup.enter.native="searchList" clearable>
              <i slot="suffix" class="el-icon-search" style="margin-top:10px;cursor:pointer" @click="searchList"></i>
            </el-input>
          </div>
          <div class="float-right">
            <el-button @click="onExport" v-loading.fullscreen.lock="loading" element-loading-text="Loading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, .48)">{{$t('graduationDesign.export')}}</el-button>
            <el-button type="primary" @click="onAdd">{{$t('graduationDesign.add')}}</el-button>
          </div>
        </div>

        <edu-table ref="assignReplyStuTable" :url="getList" @selection-change="handleSelectChange">
          <edu-table-column :label="$t('graduationDesign.graduationYear')" prop="graduationYear" min-width="80"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.college')" prop="collegeIdI18n" min-width="90"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.major')" prop="subjectIdI18n" min-width="90"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.replyGroup')" prop="defenseGroupName" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.replyLocation')" prop="defenseLocation" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.startTime')" prop="defenseStartTime" min-width="110"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.replyGroupLeader')" min-width="100">
            <template slot-scope="scope">
              {{scope.row.defenseGroupLeaderName || scope.row.defenseGroupLeaderNameOuter}}
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.replyGroupTeacher')" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="onDetail(scope.row, 'TEACHER')">{{scope.row.defenseGroupTeacherNum}}</el-button>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.replyGroupStudent')" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="onDetail(scope.row, 'STU')">{{scope.row.defenseGroupStudentNum}}</el-button>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.operation')" min-width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="onEdit(scope.row)" :disabled="scope.row.isSubmit">{{$t('graduationDesign.modify')}}</el-button>
              <el-button type="text" @click="onDelete(scope.row)" :disabled="scope.row.isSubmit">{{$t('graduationDesign.delete')}}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
      </el-card>
    </div>
    <!--新增/修改-->
    <div v-if="indexKey === 'ADD_EDIT'">
      <ReplyTeam ref="replyTeam"
                 :actionType="actionType"
                 @select-teacher-stu="selectTeacherStu"
                 :source="insource"
                 :canSelectCommittee="canSelectCommittee"
                 :replyTeamForm="replyTeamForm"
                 @auto-complete-committee="autoCompleteCommittee"
                 @reply-submit="replySubmit"
                 @reply-cancel="replyCancel"/>
    </div>
    <!--选择老师/学生-->
    <div v-if="indexKey === 'SELECT_TEACHER' || indexKey === 'SELECT_STU'">
      <SelectTutorStu
        :teacherStuInfo="teacherStuInfo"
        @teacher-stu-submit="teacherStuSubmit"
        @teacher-stu-cancel="onCancel"
        :indexKey="indexKey"/>
    </div>
  </div>
</template>
<script>
import API from "common/src/api/underGraduationDesign/assignReplyStudent";
import tools from 'common/src/views/underGraduationDesign/tools.js';
export default {
  name: 'assignReplyStudent',
  data() {
    return {
      api: API,
      getList: '/api/designservice/defenseGroup/list',
      queryForm: {
        graduationYear: '',
        collegeId: '',
        subjectId: '',
        defenseStartTime: '',
        defenseGroupName: '',
        defenseGroupLeaderName: '',
        activeAuthId: localStorage.getItem("activeAuthId")
      },
      indexKey: 'MAIN',
      source: {
        collegeOptions: [], // 学院
        subjectOptions: [] // 专业
      },
      assignSelectedData: [], // 勾选的列表数据
      breadPath: {
        label: this.$t('graduationDesign.assignReplyStudent'),
        key: "MAIN",
        children: [
          {
            key: "ADD_EDIT",
            label: "{name}",
            children: [
              {
                key: "SELECT_TEACHER",
                label: this.$t('graduationDesign.chooseTeacher'),
              },
              {
                key: "SELECT_STU",
                label: this.$t('graduationDesign.chooseStudent'),
              }
            ]
          }
        ]
      },
      loading: false,
      dialogVisible: false,
      viewDetailData: [], // 查看教师学生列表
      viewType: '',
      replyTeamForm: {},
      actionType: '', // 新增、修改
      teacherStuInfo: {}, // 选择老师、学生信息(答辩组组长，答辩组老师，答辩学生，外专业答辩学生)
      stuTeacherData: [], // 导师 学生列表
      graduationYear: '',
      insource: {
        committeeOptions: [], // 答辩委员会
        leaderOptions: [], // 答辩组长
        teacherOptions: [], // 老师
        studentOptions: [], // 学生
        foreignStudentOptions: [] // 外专业学生
      },
      canSelectCommittee: true
    };
  },
  mounted() {
    this.queryForm.graduationYear = new Date().getFullYear() + '';
    this.getCollege();
    this.searchList();
    this.getCalendarInfo();
  },
  methods: {
    searchList() {
      this.$refs.assignReplyStuTable.search(this.queryForm);
    },
    reset() {
      this.queryForm = {
        graduationYear: '',
        collegeId: '',
        subjectId: '',
        defenseStartTime: '',
        defenseGroupName: '',
        defenseGroupLeaderName: '',
        activeAuthId: localStorage.getItem("activeAuthId")
      };
      this.source.subjectOptions = [];
      this.queryForm.graduationYear = new Date().getFullYear() + '';
      this.searchList();
    },
    handleSelectChange(val) {
      this.assignSelectedData = val;
    },
    // 查校历信息
    async getCalendarInfo() {
      const calendarInfo = await this.getCalendarId();
      this.schoolCalendarInfo = await this.getSchoolCalendar(calendarInfo.id);
      this.graduationYear = this.schoolCalendarInfo.gradePartTwo;

    },
    getCalendarId() {
      return this.api.getCalendarId().then(res => {
        return res.data.schoolCalendar;
      }).catch();
    },
    getSchoolCalendar(calendarId) {
      return this.api.getSchoolCalendar(calendarId).then(res => {
        return res.data;
      });
    },
    // 查学院
    getCollege() {
      this.api.getCollege().then(res => {
        this.source.collegeOptions = res;
      });
    },
    handleGradeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.collegeId) {
        this.handleCollegeChange(this.queryForm.collegeId);
      }
    },
    // 根据毕业年份和学院查专业
    handleCollegeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.graduationYear) {
        const params = {
          grade: this.queryForm.graduationYear,
          college: val
        };
        this.api.getSubject(params).then(res => {
          this.source.subjectOptions = res.data;
        }).catch();
      }
    },
    // 新增
    onAdd() {
      this.actionType = "ADD";
      this.indexKey = "ADD_EDIT";
      this.replyTeamForm = {
        graduationYear: this.graduationYear,
        collegeId: '',
        subjectId: '',
        defenseGroupName: '',
        defenseLocation: '',
        defenseStartTime: '',
        committeeMemberCodeList: [],
        defenseGroupLeader: '',
        teacherCodeList: [],
        studentCodeList: [],
        otherSubjectStudentCodeList: []
      };
      this.insource = {
        committeeOptions: [], // 答辩委员会
        leaderOptions: [], // 答辩组长
        teacherOptions: [], // 老师
        studentOptions: [], // 学生
        foreignStudentOptions: [] // 外专业学生
      };
    },
    // 选择老师 学生
    selectTeacherStu(data) {
      this.canSelectCommittee = this.$refs['replyTeam'].canSelectCommittee;
      this.indexKey = data.isTeacher ? 'SELECT_TEACHER' : 'SELECT_STU';
      this.teacherStuInfo = { ...data };
    },
    onCancel() {
      this.indexKey = "ADD_EDIT";
    },
    // 选择完老师(学生)提交 (新增或编辑)
    teacherStuSubmit(checkedData, data) {
      const columnType = checkedData.columnType;
      // 下拉框回显数据
      switch (columnType) {
        // 答辩委员会成员
        case "allCommitteeMemberCodeList":
          this.replyTeamForm["defenseCommitteeMembers"] = (checkedData.rightCheckedList || []).join(',');
          this.replyTeamForm["defenseCommitteeMembersOuter"] = (checkedData.rightCheckedOuterList || []).join(',');
          this.replyTeamForm["committeeMemberCodeList"] = checkedData.rightCheckedList;
          this.replyTeamForm["committeeMemberCodeOuterList"] = checkedData.rightCheckedOuterList;
          this.replyTeamForm["defenseCommitteeMemberList"] = data.innerStuTeacherData;
          this.replyTeamForm["defenseCommitteeMemberOutList"] = data.outerStuTeacherData;
          this.replyTeamForm["allCommitteeMemberCodeList"] = this.mergeArrays(checkedData.rightCheckedList, checkedData.rightCheckedOuterList);
          this.insource["committeeOptions"] = this.mergeArrays(data.innerStuTeacherData, data.outerStuTeacherData);
          break;
        // 答辩组组长 值为string类型
        case "allDefenseGroupLeader":
          const defenseGroupLeader = checkedData.rightCheckedList.length ? checkedData.rightCheckedList[0] : '';
          const defenseGroupLeaderOuter = checkedData.rightCheckedOuterList.length ? checkedData.rightCheckedOuterList[0] : '';
          this.replyTeamForm["defenseGroupLeader"] = defenseGroupLeader;
          this.replyTeamForm["defenseGroupLeaderOuter"] = defenseGroupLeaderOuter;
          this.replyTeamForm["defenseGroupLeaderList"] = data.innerStuTeacherData;
          this.replyTeamForm["defenseGroupLeaderOutList"] = data.outerStuTeacherData;
          this.replyTeamForm["allDefenseGroupLeader"] = defenseGroupLeader || defenseGroupLeaderOuter;
          this.insource["leaderOptions"] = this.mergeArrays(data.innerStuTeacherData, data.outerStuTeacherData);
          break;
        // 答辩组老师
        case "allTeacherCodeList":
          this.replyTeamForm["defenseGroupTeachers"] = (checkedData.rightCheckedList || []).join(',');
          this.replyTeamForm["defenseGroupTeachersOuter"] = (checkedData.rightCheckedOuterList || []).join(',');
          this.replyTeamForm["teacherCodeList"] = checkedData.rightCheckedList;
          this.replyTeamForm["teacherCodeOuterList"] = checkedData.rightCheckedOuterList;
          this.replyTeamForm["defenseGroupTeacherList"] = data.innerStuTeacherData;
          this.replyTeamForm["defenseGroupTeacherOutList"] = data.outerStuTeacherData;
          this.replyTeamForm["allTeacherCodeList"] = this.mergeArrays(checkedData.rightCheckedList, checkedData.rightCheckedOuterList);
          this.insource["teacherOptions"] = this.mergeArrays(data.innerStuTeacherData, data.outerStuTeacherData);
          break;
        // 答辩学生
        case "studentCodeList":
          this.replyTeamForm["studentCodeList"] = checkedData.rightCheckedList;
          this.insource["studentOptions"] = data.innerStuTeacherData;
          break;
        // 外专业学生
        case "otherSubjectStudentCodeList":
          this.replyTeamForm["otherSubjectStudentCodeList"] = checkedData.rightCheckedList;
          this.insource["foreignStudentOptions"] = data.innerStuTeacherData;
          break;
        default:
          break;
      }
      this.autoCompleteCommittee();
      this.indexKey = "ADD_EDIT";
    },
    autoCompleteCommittee (options = []) {
      this.insource["committeeOptions"] = this.mergeArrays(this.replyTeamForm['defenseCommitteeMemberList'], this.replyTeamForm['defenseCommitteeMemberOutList']);
    },
    // 查看答辩组老师 学生
    onDetail(row, type) {
      this.viewType = type;
      let roleType = type === 'TEACHER' ? '0' : '1';
      this.api.getTeacherStuInfo(row.id, roleType).then(res => {
        this.viewDetailData = res.data;
        this.dialogVisible = true;
      }).catch();
    },
    // 关闭
    closeDialog() {
      this.dialogVisible = false;
    },
    // 下拉框格式化
    formatOptions(data = [], label, value) {
      let result = [];
      data.forEach(item => {
        result.push({
          label: item[label],
          value: item[value],
        });
      });
      return result;
    },
    // 修改
    onEdit(row) {
      // 查答辩组信息
      this.api.getDetail(row.id).then(res => {
        this.canSelectCommittee = true;
        this.actionType = "EDIT";
        this.indexKey = "ADD_EDIT";
        const data = res.data;
        this.replyTeamForm = {
          ...data,
          graduationYear: (row.graduationYear || '') + ''
        };
        this.dealWithDetailInfo(data);
        // 下拉框数据
        this.insource = {
          // 答辩委员会
          committeeOptions:
            this.formatOptions(this.mergeArrays(data.defenseCommitteeMemberList, data.defenseCommitteeMemberOutList), "teacherNameAndId", "teacherId"),
          // 答辩组长
          leaderOptions:
            this.formatOptions(this.mergeArrays(data.defenseGroupLeaderList, data.defenseGroupLeaderOutList), "teacherNameAndId", "teacherId"),
          // 老师
          teacherOptions:
            this.formatOptions(this.mergeArrays(data.defenseGroupTeacherList, data.defenseGroupTeacherOutList), "teacherNameAndId", "teacherId"),
          // 学生
          studentOptions:
            this.formatOptions(data.defenseGroupStudentList || [], "studentNameAndId", "studentId"),
          // 外专业学生
          foreignStudentOptions:
            this.formatOptions(data.defenseGroupOtherSubjectStudentList || [], "studentNameAndId", "studentId")
        };
      });
    },
    // 处理详情数据
    dealWithDetailInfo (data) {
      // 答辩委员会
      this.replyTeamForm.committeeMemberCodeList = this.convertStrToArray(data.defenseCommitteeMembers);
      this.replyTeamForm.committeeMemberCodeOuterList = this.convertStrToArray(data.defenseCommitteeMembersOuter);
      this.replyTeamForm.allCommitteeMemberCodeList =
        this.mergeArrays(this.replyTeamForm.committeeMemberCodeList, this.replyTeamForm.committeeMemberCodeOuterList);

      // 答辩组组长
      this.replyTeamForm.allDefenseGroupLeader = data.defenseGroupLeader || data.defenseGroupLeaderOuter;

      // 答辩组老师
      this.replyTeamForm.teacherCodeList = this.convertStrToArray(data.defenseGroupTeachers);
      this.replyTeamForm.teacherCodeOuterList = this.convertStrToArray(data.defenseGroupTeachersOuter);
      this.replyTeamForm.allTeacherCodeList =
        this.mergeArrays(this.replyTeamForm.teacherCodeList, this.replyTeamForm.teacherCodeOuterList);
      this.replyTeamForm.studentCodeList = this.convertStrToArray(data.defenseGroupStudents);
      this.replyTeamForm.otherSubjectStudentCodeList =
        (data.defenseGroupOtherSubjectStudentList || []).map(item => item.studentId);
    },
    convertStrToArray(str) {
      if (!str) {
        return [];
      }
      return str.split(',');
    },
    // 数据合并,并去重
    mergeArrays() {
      if (!arguments.length){
        return [];
      }
      let result = [];
      for(var i = 0; i < arguments.length; i++) {
        const item = arguments[i];
        if (item && item.length) {
          result = result.concat(item)
        }
      }
      return [...new Set(result)];
    },
    // 新增，编辑提交
    replySubmit(data, actionType) {
      delete data['allInnerTeachers'];
      delete data['allOuterTutors'];
      let req = null;
      if (actionType === "ADD") {
        req = this.api.insert(data);
      } else {
        req = this.api.update(data);
      }
      req.then(res => {
        this.$message.success(this.$t('graduationDesign.submitSuccess'));
        this.indexKey = "MAIN";
        this.searchList();
      }).catch();
    },
    replyCancel() {
      this.indexKey = "MAIN";
      this.searchList();
    },
    // 删除
    onDelete(row) {
      this.$delConfirm(this.$t('graduationDesign.deleteConfirm'), this.$t('graduationDesign.delete')).then(() => {
        this.api.delete(row.id).then(res => {
          this.$message.success(this.$t('graduationDesign.deleteSuccess'));
          this.searchList();
        }).catch();
      });
    },
    // 导出
    onExport() {
      const params = {
        condition: this.queryForm,
        selectList: this.assignSelectedData
      };
      this.api.export(params).then(res => {
        if (res.code == 200) {
          // this.delayRequest(res.data.key);
          tools.downloadFile(res.data.key, "分配答辩组学生.xls", null, this);
        }
      });
    },
    // 查文件导出状态，等待导出
    async delayRequest(key) {
      this.loading = true;
      await new Promise(resolve => setTimeout(resolve, 3000));
      this.api.getExportStatus(key).then(res => {
        this.loading = false;
        if (res.code === 200 && res.data.status) {
          let path = 'api/designservice/common/export?path=' + res.data.path;
          window.open(path);
        } else {
          this.delayRequest(key);
        }
      }).catch(err => {
        this.loading = false;
        this.delayRequest(key);
      });
    }
  },
  components: {
    ReplyTeam: () => import('./components/replyTeam'),
    SelectTutorStu: () => import('./components/selectTutorStu'),
    TeacherStuInfoDialog: () => import('./components/teacherStuInfoDialog')
  }
}
</script>
<style lang="scss" scoped>
.assign-reply-stu {
    .search-item {
        width: 100%;
    }
}
</style>
